/*
===========================================================================
Copyright (C) 2013-2014 Avotu Briezhaudzetava

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.

===========================================================================
*/

//
// includes
//
#include "gui_login.h"
#include "ui_gui_login.h"
#include "main.h"
#include "gui_main.h"
#include "hash.h"
#include <QMessageBox>

/*
================
construct
================
*/
Gui_Login::Gui_Login( QWidget *parent ) : QDialog( parent ), ui( new Ui::Gui_Login ) {
    ui->setupUi( this );
    this->counter = 0;

    // fill user names
    foreach ( UserEntry *uPtr, m.userList )
        this->ui->comboUsers->addItem( uPtr->name());

    // get gui
    Gui_Main *guiPtr = qobject_cast<Gui_Main*>( this->parent());
    if ( guiPtr != NULL )
        this->connect( this, SIGNAL( rejected()), guiPtr, SLOT( close()));
}

/*
================
destruct
================
*/
Gui_Login::~Gui_Login() {
    this->disconnect( this, SIGNAL( rejected()));
    delete ui;
}

/*
================
buttonExit->clicked
================
*/
void Gui_Login::on_buttonExit_clicked() {
    this->reject();
}

/*
================
buttonLogin->clicked
================
*/
void Gui_Login::on_buttonLogin_clicked() {
    UserEntry *uPtr = m.userForName( this->ui->comboUsers->currentText());
    if ( uPtr == NULL )
        this->reject();

    if ( QString::compare( uPtr->password(), Hash::encrypt( this->ui->textPassword->text()))) {
        QMessageBox::warning( this, this->tr( "Login" ),
                                    this->tr( "Password mismatch" ), QMessageBox::Ok );
        this->counter += 1;
        this->ui->textPassword->clear();

        // quit on three errors
        if ( this->counter == 3 )
            this->reject();

        return;
    }

    Gui_Main *guiPtr = qobject_cast<Gui_Main*>( this->parent());
    if ( guiPtr != NULL )
        guiPtr->setEnabled( true );

    this->accept();
}
